package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.query.QueryObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Administrator on 2020/3/6.
 */
@Service
public class EmployeeServiceImpl implements IEmployeeService {
	@Autowired@SuppressWarnings("all")
	private EmployeeMapper employeeMapper;
	@Override
	public void delete(Long id) {
		//先删除关系,再删除员工对象
		employeeMapper.deleteRelation(id);
		employeeMapper.deleteByPrimaryKey(id);
	}

	@Override
	public void save(Employee employee, Long[] ids) {
		employeeMapper.insert(employee);
	}

	public Employee get(Long id) {
		Employee employee = employeeMapper.selectByPrimaryKey(id);
		return employee;
	}

	@Override
	public List<Employee> listAll() {
		List<Employee> employees = employeeMapper.selectAll();
		return employees;
	}

	@Override
	public void update(Employee employee, Long[] ids) {
		employeeMapper.updateByPrimaryKey(employee);
	}
	@Override
	public void saveOrUpdate(Employee employee, Long[] ids){
		if(employee.getId() == null){
			Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getName());
			employee.setPassword(md5Hash.toString());
			employeeMapper.insert(employee);
		}else{
			//先删除该对象中的关系,后面保存新关系
			employeeMapper.deleteRelation(employee.getId());
			employeeMapper.updateByPrimaryKey(employee);
		}
		//维护关系
		if(ids != null){
			for(Long roleId : ids){
				employeeMapper.insertRelation(employee.getId(),roleId);
			}
		}
	}
	@Override
	public Employee selectByUsernameAndPassword(String username, String password) {
		Employee employee = employeeMapper.selectByUsernameAndPassword(username, password);
		if(employee==null){
			throw new RuntimeException("账户或密码错误");
		}
		return employee;
	}

	@Override
	public int queryForCount(QueryObject qo) {
		return 0;
	}

	@Override
	public PageInfo queryForList(QueryObject qo) {
		PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
		List<Employee> employees = employeeMapper.queryForList(qo);
		return new PageInfo(employees);
	}

	@Override
	public List<String> selectExpByEmpId(Long id) {
		return employeeMapper.selectExpByEmpId(id);
	}

	@Override
	public void batchDelete(Long[] ids) {
		employeeMapper.batchDelete(ids);
		employeeMapper.batchDeleteRelation(ids);
	}

	public Employee getByName(String name) {
		Employee employee = employeeMapper.getByName(name);
		return employee;
	}
}
